//
//  AppDelegate.m
//  OA
//
//  Created by yy on 17/6/5.
//  Copyright © 2017年 yy. All rights reserved.
//

#import "AppDelegate.h"
#import "MessageDetailViewController.h"

#import "IQKeyboardManager.h"
// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

// 如果需要使用idfa功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>

//AppKey f650e00c710a771bfc12fe80
@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    
    //Optional
    // 获取IDFA
    // 如需使用IDFA功能请添加此代码并在初始化方法的advertisingIdentifier参数中填写对应值
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // Required
//    apsForProduction
//    1.3.1版本新增，用于标识当前应用所使用的APNs证书环境。
//    0 (默认值)表示采用的是开发证书，1 表示采用生产证书发布应用。
//    注：此字段的值要与Build Settings的Code Signing配置的证书环境一致
    
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:@"f650e00c710a771bfc12fe80"
                          channel:@"APP Store"
                 apsForProduction:0
            advertisingIdentifier:advertisingId];
    
//    //2.1.9版本新增获取registration id block接口。
//    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
//        if(resCode == 0)
//        {
//            // iOS10获取registrationID放到这里了, 可以存到缓存里, 用来标识用户单独发送推送
//            //     ----- login result -----
//            //        uid:10374013045
//            //        registrationID:13165ffa4e3cc9f23f6
//            NSLog(@"registrationID获取成功：%@",registrationID);
//            [[NSUserDefaults standardUserDefaults] setObject:registrationID forKey:@"registrationID"];
//            [[NSUserDefaults standardUserDefaults] synchronize];
//        }
//        else
//        {
//            NSLog(@"registrationID获取失败，code：%d",resCode);
//        }
//    }];
//    //获取iOS的推送内容需要在delegate类中注册通知并实现回调方法。
//    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
//    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];

//———————————————————————————————以上推送———————————————————————————————————————
    

    
//_______________________登录_________________________________________________________
    LoginViewController *loginVC = Y_storyBoard_id(@"LoginViewController");
    self.nav = [[UINavigationController alloc] initWithRootViewController:loginVC];
    self.window.rootViewController = self.nav;
    
    
//___________键盘_____________________________________________________________________
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = NO;
    
//___________引导页__________________________________________________________________
    UITextView *tex = [[UITextView alloc]init];
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.frame = CGRectMake(0, 0, kScreen_Width, kScreen_Height);
    scrollView.pagingEnabled = YES;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.bounces = NO;
    [scrollView setContentSize:CGSizeMake(kScreen_Width * 3, kScreen_Height)];
    for (NSInteger index = 0; index < 3; index ++) {
        UIImageView *imageView = [[UIImageView alloc]init];
        NSString *imageName = [NSString stringWithFormat:@"启动页%ld",index + 1];
        imageView.image = Y_IMAGE(imageName);
        imageView.frame = CGRectMake(kScreen_Width * index, 0, kScreen_Width, kScreen_Height);
        
        [scrollView addSubview:imageView];
        
    }
    //___________引导页最后页的btn__________________________________________________________________
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.bounds = CGRectMake(0, 0, 140, 45);
//    [button setBackgroundColor:[UIColor redColor]];
    [button.titleLabel setFont:[UIFont systemFontOfSize:40]];
    button.center = CGPointMake(kScreen_Width / 2 + kScreen_Width * 2, kScreen_Height - 70.0 / 667 * kScreen_Height);
    [button setBackgroundImage:Y_IMAGE(@"") forState:UIControlStateNormal];
    [button setTitle:@"" forState:UIControlStateNormal];
    //    [button setBackgroundColor:[UIColor redColor]];
    [button.titleLabel setFont:[UIFont systemFontOfSize:17 weight:1]];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    //    [button setBackgroundColor:[UIColor clearColor]];
    [button addTarget:self action:@selector(intoHome:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:button];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"isFirst"]) {
        self.window.rootViewController = self.nav;
        
    } else {
        UIViewController *vc = [[UIViewController alloc]init];
        vc.view.backgroundColor = [UIColor whiteColor];
        [vc.view addSubview:scrollView];
        self.window.rootViewController  = vc;
    }
    [self.window makeKeyAndVisible];
    
    
//________________________________________________________________________________
    if ([ShareUserInfo sharedUserInfo].lxrArr == nil) {
        [ShareUserInfo sharedUserInfo].lxrArr = @[].mutableCopy;
    }
    if ([ShareUserInfo sharedUserInfo].csArr == nil) {
        [ShareUserInfo sharedUserInfo].csArr = @[].mutableCopy;
    }
    return YES;
}
- (void)intoHome:(UIButton *)sender {
    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"isFirst"];
    self.window.rootViewController = self.nav;
}


#pragma mark —————— 

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSLog(@"willPresentNotification");
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSLog(@"didReceiveNotificationResponse");
    NSDictionary * userInfo = response.notification.request.content.userInfo;
     NSLog(@"userInfo1  %@",userInfo);
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    
    
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"didReceiveRemoteNotificationfetchCompletionHandler");
    NSLog(@"userInfo2  %@",userInfo);

//    MessageDetailViewController *detailListVc = Y_storyBoard_id(@"MessageDetailViewController");
    
    MessageModel *model = [MessageModel objectWithKeyValues:userInfo];
    //pushTypeId 105通知；运维 104； 101日志； 申请类102+01请假   加班02 出差03 外勤04 补卡05；审批类103+01请假 加班02 出差03 外勤04 补卡05
    /**
     userInfo2  {
     "_j_business" = 1;
     "_j_msgid" = 20266198718588605;
     "_j_uid" = 10374013045;
     aps =     {
     alert = "\U6768\U5bb6\U5b87\U53d1\U4e86\U4e00\U6761\U901a\U77e5";
     badge = 1;
     sound = "test1.caf";
     };
     pushTypeId = "105:00000093:00000094:00000098:00000099";
     }*/
    
//    NSArray *arrOfData = [model.pushTypeId  componentsSeparatedByString:@":"];
//    if (arrOfData.count<2) {
//        [MBProgressHUD showError:@"推送获取失败！"];
//        return;
//    }
    switch ([model.pushTypeId intValue]) {
            //日志
        case 101:
            [self rz:model];
            break;
            //通知
        case 105:
            [self tz:model];
            break;
            //运维
        case 104:
            [self yw:model];
            break;
            //考勤打卡提醒
        case 2:
            
            break;
            //请假
        case 10201:
            [self qj:model isShenHePerSon:YES];
            break;
        case 10301:
            [self qj:model isShenHePerSon:NO];
            break;
            //加班
        case 10202:
            [self jb:model isShenHePerSon:YES];
            break;
        case 10302:
            [self jb:model isShenHePerSon:NO];
            break;
            
            //出差
        case 10203:
            [self cc:model isShenHePerSon:YES];
            break;
        case 10303:
            [self cc:model isShenHePerSon:NO];
            break;
            //外勤
        case 10204:
            [self wq:model isShenHePerSon:YES];
            break;
        case 10304:
            [self wq:model isShenHePerSon:NO];
            break;
            //补卡
        case 10205:
            [self bk:model isShenHePerSon:YES];
            break;
        case 10305:
            [self bk:model isShenHePerSon:NO];
            break;
            
        default:
            
            break;
    }

    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);

}

#pragma mark —————— 日志通知类
- (void)rz:(MessageModel*)model{
    BlogDetailViewController *vc = VCInSB(@"BlogDetailViewController", @"FirstViewControllers");
//    vc.blogId = [model.pushTypeId componentsSeparatedByString:@":"][1];
    vc.blogId =model.id;
    vc.hidesBottomBarWhenPushed = YES;
    [self pushVcOfDetailVc:vc];
}

- (void)tz:(MessageModel*)model{
    NoticeDetailViewController *noticeDetailVc = VCInSB(@"NoticeDetailViewController", @"SecondViewControllers");

//    noticeDetailVc.idOfdetail = [model.pushTypeId componentsSeparatedByString:@":"][1];
    noticeDetailVc.idOfdetail = model.id;
    noticeDetailVc.hidesBottomBarWhenPushed = YES;
    [self pushVcOfDetailVc:noticeDetailVc];
}

#pragma mark —————— 运维
- (void)yw:(MessageModel*)model{

//    if ( [model.status intValue] == 2) {
//    
//        //已完成详情
//        MainteanceShowViewController *maintenanceShowVc = VCInSB(@"MainteanceShowViewController", @"ThirdViewControllers");
//        maintenanceShowVc.idOfStr = [model.pushTypeId componentsSeparatedByString:@":"][1];
//        maintenanceShowVc.hidesBottomBarWhenPushed = YES;
//        [self pushVcOfDetailVc:maintenanceShowVc];
//
//    
//    }else{
//        MaintenanceAddRelatedViewController *maintenanceAddVc = VCInSB(@"MaintenanceAddRelatedViewController", @"ThirdViewControllers");
//        if ( [model.status intValue] == 0) {
//            maintenanceAddVc.typeOfNum = 0;//分配
//        }else{
//            maintenanceAddVc.typeOfNum = 1;//完成
//        }
//        maintenanceAddVc.idOfStr = [model.pushTypeId componentsSeparatedByString:@":"][1];
//        maintenanceAddVc.hidesBottomBarWhenPushed = YES;
//        [self pushVcOfDetailVc:maintenanceAddVc];
//    }
    
    MaintenanceViewController *maintenanceListVc = VCInSB(@"MaintenanceViewController", @"ThirdViewControllers");
    maintenanceListVc.isMyMaintenanceList = YES;
    maintenanceListVc.hidesBottomBarWhenPushed = YES;
    [self pushVcOfDetailVc:maintenanceListVc];
}


#pragma mark —————— 申请审核类

- (void)jb:(MessageModel *)model isShenHePerSon:(BOOL)isShenhe{
    if (isShenhe) {
        [self type:@"1" model:model isShenHe:isShenhe];
    }else{
        [self finishType:@"1" model:model isShenHe:isShenhe];
    }
    
}
- (void)qj:(MessageModel*)model isShenHePerSon:(BOOL)isShenhe{
    if (isShenhe) {
       [self type:@"3" model:model isShenHe:isShenhe];
    }else{
       [self finishType:@"3" model:model isShenHe:isShenhe];
    }
    
}
- (void)cc:(MessageModel *)model isShenHePerSon:(BOOL)isShenhe{
    if (isShenhe) {
        [self type:@"5" model:model isShenHe:isShenhe];
    }else{
        [self finishType:@"5" model:model isShenHe:isShenhe];
    }
}
- (void)wq:(MessageModel *)model isShenHePerSon:(BOOL)isShenhe{
    if (isShenhe) {
        [self type:@"7" model:model isShenHe:isShenhe];
    }else{
        [self finishType:@"7" model:model isShenHe:isShenhe];
    }
}
- (void)bk:(MessageModel *)model isShenHePerSon:(BOOL)isShenhe{
  
    if (isShenhe) {
        [self type:@"9" model:model isShenHe:isShenhe];
    }else{
        [self finishType:@"9" model:model isShenHe:isShenhe];
    }
}

- (void)type:(NSString*)typeStr model:(MessageModel *)model isShenHe:(BOOL)isShenhe{
    AuditViewController  *auditViewVc = VCInSB(@"AuditViewController", @"SecondViewControllers");
//    NSString *idS = [model.pushTypeId componentsSeparatedByString:@":"][1];
    NSString *idS = model.id;
    idS = idS.length<=36?idS:[idS substringWithRange:NSMakeRange(idS.length-36, 36)];
    auditViewVc.idOfAudit = idS;
    auditViewVc.typeStr = typeStr;
//    auditViewVc.isOperationer = isShenhe;
    auditViewVc.hidesBottomBarWhenPushed = YES;
    [self pushVcOfDetailVc:auditViewVc];
}
- (void)finishType:(NSString*)typeStr model:(MessageModel *)model isShenHe:(BOOL)isShenhe{
    AuditTwoViewController  *auditTwoViewVc = VCInSB(@"AuditTwoViewController", @"SecondViewControllers");
//    NSString *idS = [model.pushTypeId componentsSeparatedByString:@":"][1];
    NSString *idS = model.id;
    idS = idS.length<=36?idS:[idS substringWithRange:NSMakeRange(idS.length-36, 36)];
    auditTwoViewVc.idOfAudit = idS;
    auditTwoViewVc.typeStr = typeStr;
    auditTwoViewVc.hidesBottomBarWhenPushed = YES;
    [self pushVcOfDetailVc:auditTwoViewVc];
//    [self.navigationController pushViewController:auditTwoViewVc animated:YES];
}



- (void)pushVcOfDetailVc:(UIViewController *)detailvc{
    UIViewController *vc = self.window.rootViewController ;
    //红角标消失
    NSInteger num =  [UIApplication sharedApplication].applicationIconBadgeNumber;
    [UIApplication sharedApplication].applicationIconBadgeNumber = num==0?0:num-1;
    if ([vc isKindOfClass:[UINavigationController class]]) {
        UIViewController * nav = [(UINavigationController *)vc visibleViewController];
        UINavigationController *nav1 = (UINavigationController *)nav;
        [nav1 setNavigationBarHidden:NO animated:NO];
        [nav1 pushViewController:detailvc animated:YES];
        //
    }else if([vc isKindOfClass:[UITabBarController class]]){
        UITabBarController * tabVC = (UITabBarController *)vc;
        UINavigationController *Rootvc = [tabVC.viewControllers objectAtIndex:tabVC.selectedIndex];
        [Rootvc pushViewController:detailvc animated:YES];
        
    }
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSLog(@"didReceiveRemoteNotification");
    NSLog(@"userInfo3  %@",userInfo);
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}






- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
